package com.af.monitorModule.common.util;

import com.af.monitorModule.generator.entity.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenUtil {
//    /**
//     * 过期时间 五天
//     */
    private static final long EXPIRE_TIME = 1000*60*60*24*5;
    /**
     * token密钥
     */
    private static final String TOKEN_SECRET = "fk58fHdj3sgx63cnDhWz82j40hk7-b=sd,3hxu3";



    public  String getToken(User user){
        //过期时间
        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        //token加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        Map<String,Object> hand = new HashMap<>(2);
        hand.put("type","JWT");
        hand.put("alg","HMAC256");
        //放入信息，生成签名
        return JWT.create()
                .withHeader(hand)
                .withClaim("userId",user.getUserId())
                .withClaim("userLoginName",user.getUserName())
                .withExpiresAt(date)
                .sign(algorithm);
    }


    //解密
    public  DecodedJWT verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
            return verifier.verify(token);
        } catch (Exception e){
            return null;
        }
    }

}
